const router = require('koa-router')()
const REDIS = require('../util//util.redis')
const $util = require('../util/util')
const wechat = require('../util/wechat')

// 获取微信配置
router.post('/wechat/api/v1/get_config', async (ctx, next) => {
  let ret = await REDIS.getRedis('yezi_jsapi_ticket')
  let sign
  // console.log(ret)
  if (ret) {
    console.log('resdis ticket log:', ret)
    sign = await wechat.sign(ret, ctx.request.body.url)
  } else {
    // 获取ticket
    let res = await wechat.getJsapiTicket()
    console.log('redis no cache from wechat getJsapiTicket:', res)
    sign = await wechat.sign(res.ticket, ctx.request.body.url)
  }

  ctx.body = $util.jsonWrite(sign, {
    flag: true,
    msg: '获取微信配置参数成功'
  })
})

// 微信公众号用户创建菜单
router.get('/create_menu', async (ctx, next) => {
  wechat.createMenu(ctx.query)
  ctx.body = $util.jsonWrite(null, {
    flag: true,
    msg: '微信菜单配置成功'
  })
})

// 微信配置
router.all('/weixin', async (ctx, next) => {
  // console.log(req.url)
  let token = 'service'
  const crypto = require('crypto')
  let signature = ctx.query.signature
  let timestamp = ctx.query.timestamp
  let nonce = ctx.query.nonce
  let echostr = ctx.query.echostr
 // 1. 将token、timestamp、nonce三个参数进行字典序排序
  let array = [token, timestamp, nonce]
  array.sort()
 // console.log(array, signature);
  let str = array.toString().replace(/,/g, '')
 // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
  let sha1Code = crypto.createHash('sha1')
  let code = sha1Code.update(str, 'utf-8').digest('hex')
 // console.log(code);
 // 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
  if (code === signature) {
    ctx.body = echostr
  } else {
    console.log('error')
  }
})

// 接受客服消息
router.post('/weixin', (ctx, next) => {
  // console.log(req.query, req.body)
  let decrypt = {
    'ToUserName': ctx.query.openid,
    'FromUserName': 'Wuyangjun155',
    'CreateTime': ctx.query.timestamp,
    'MsgType': 'transfer_customer_service'
  }
  // console.log(decrypt)
  ctx.body = decrypt
})

module.exports = router
